import json
import logging
import os
import zipfile
from typing import Any, Dict, List

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


class BioInfoError(Exception):
    """生物信息工具相关的自定义异常"""
    pass


class ConfigManager:
    """配置文件管理器"""
    
    def __init__(self, config_path: str = 'config.ini'):
        """初始化配置管理器"""
        import configparser
        self.config = configparser.ConfigParser()
        try:
            self.config.read(config_path, encoding='utf-8')
        except Exception as e:
            raise BioInfoError(f"读取配置文件失败: {e}")
    
    def get(self, section: str, key: str) -> str:
        """获取配置值"""
        try:
            return self.config.get(section, key)
        except (configparser.NoSectionError, configparser.NoOptionError) as e:
            raise BioInfoError(f"配置项未找到: {section}.{key}")


class DataFormatter:
    """数据格式化工具（公共部分）"""
    
    @staticmethod
    def save_json(data: Dict[str, Any], filename: str) -> None:
        """保存JSON数据到文件"""
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=2, ensure_ascii=False)
            logger.info(f"JSON结果已保存到: {filename}")
        except Exception as e:
            raise BioInfoError(f"保存JSON文件失败: {e}")
    
    @staticmethod
    def create_zip_archive(filename: str, include_csv: bool = True, 
                         include_md: bool = False) -> str:
        """创建包含所有格式文件的ZIP归档
        
        Args:
            filename: JSON文件的路径
            include_csv: 是否包含CSV文件（默认True）
            include_md: 是否包含Markdown文件（默认False）
            
        Returns:
            创建的ZIP文件路径
        """
        # 生成ZIP文件名
        zip_filename = filename.replace('.json', '.zip')
        
        # 创建ZIP文件并添加相关文件
        with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
            # 添加JSON文件
            if os.path.exists(filename):
                zipf.write(filename, os.path.basename(filename))
            
            # 可选添加CSV文件
            if include_csv:
                csv_filename = filename.replace('.json', '.csv')
                if os.path.exists(csv_filename):
                    zipf.write(csv_filename, os.path.basename(csv_filename))
            
            # 可选添加Markdown文件
            if include_md:
                md_filename = filename.replace('.json', '.md')
                if os.path.exists(md_filename):
                    zipf.write(md_filename, os.path.basename(md_filename))
        
        logger.info(f"ZIP归档已创建: {zip_filename}")
        return zip_filename